const fs = require('fs');
const path = require('path');
const schedule = require('node-schedule');

/**
 * 清理指定目录下创建时间超过指定天数的文件
 * @param {string} dirPath - 要清理的目录路径
 * @param {number} days - 天数阈值
 */
function cleanOldFiles(dirPath, days) {
  try {
    const files = fs.readdirSync(dirPath);
    const now = Date.now();
    const threshold = days * 24 * 60 * 60 * 1000; // 转换为毫秒

    files.forEach(file => {
      const filePath = path.join(dirPath, file);
      const stat = fs.statSync(filePath);
      
      // 检查是否为文件（而非目录）
      if (stat.isFile()) {
        const fileAge = now - stat.birthtimeMs;
        
        // 如果文件创建时间超过阈值，则删除文件
        if (fileAge > threshold) {
          fs.unlinkSync(filePath);
          console.log(`Deleted old file: ${filePath}`);
        }
      }
    });
  } catch (error) {
    console.error('Error cleaning old files:', error);
  }
}

/**
 * 设置每天凌晨0点执行清理任务
 */
function scheduleCleanupTask() {
  // 定义每天凌晨0点执行的规则
  const rule = new schedule.RecurrenceRule();
  rule.hour = 0;
  rule.minute = 0;
  rule.second = 0;
  
  // 立即执行一次清理
  cleanOldFiles(path.join(__dirname, '../../static/upload'), 7);
  
  // 安排定时任务
  schedule.scheduleJob(rule, () => {
    cleanOldFiles(path.join(__dirname, '../../static/upload'), 7);
  });
  
  console.log('Scheduled cleanup task for static/upload directory at 00:00 daily');
}

module.exports = {
  scheduleCleanupTask
};
